const Router = require('koa-router');
const router = new Router();
const {db, QueryTypes} = require("../../models/db");
router.post('/deliver/delCargo', async ctx => {
    let tenantId = ctx.user.tenantId;
    let cargoId = ctx.request.body.cargoId;
    let uid = ctx.user.id;
    let cname = ctx.user.name;
    let cargo = await db.models['cargo'].findOne({
        where: {
            id: cargoId
        }
    })
    if (cargo.state != 1) {
        return ctx.err('已确认收货, 不能删除');
    }
    // let usr = await db.models['admin'].findOne({
    //     where: {
    //         id: uid
    //     },
    //     attributes: ['canDelDeliver']
    // })
    // if (usr.canDelDeliver != 1) {
    //     return ctx.err('没有删除票据的权限')
    // }
    let cin = await db.models['cargoInvoice'].findAll({
        where: {
            cargoId: cargoId
        }
    })
    cargo.infos = cin;
    await db.transaction(async () => {
        // await db.models['cargoLog'].create({
        //     tenantId,
        //     cby: uid,
        //     cbyName: cname,
        //     op: '删除',
        //     cargoId,
        //     content: JSON.stringify(cargo)
        // }, )
        // 更新票据为未送货
        let sql =  `update invoice set isLoad=0 where id in (select iid from cargo_invoice where cargoId=${cargoId}) `
        await db.query(sql, {type: QueryTypes.UPDATE})
        // 再删除配送单
        await db.models['cargo'].destroy({
            where: {
                id: cargoId
            }
        })
        await db.models['cargoInvoice'].destroy({
            where: {
                cargoId: cargoId,
                tenantId: tenantId
            }
        })
    })
    // 更新送货员为票据的送货员
    return ctx.suc("已删除");
})


module.exports = router;
